package com.dongxing.concyrrency.chapter6;

import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class ThreadInterrupt2 {

    private final static Object MONITOR = new Object();


    public static void main(String[] args) {

        Thread t1 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    // 线程打断  sleep的方式
//                    try {
//                        TimeUnit.SECONDS.sleep(10);
//                    } catch (InterruptedException e) {
//                        System.out.println("收到打断信号");
//                        e.printStackTrace();
//                    }
//                    System.out.println(">>>" + this.isInterrupted());

                    // 线程打断  wait的方式
                    while (true) {
                        synchronized (MONITOR) {
                            try {
                                MONITOR.wait(10);
                            } catch (InterruptedException e) {
                                System.out.println("收到打断信号");
                                e.printStackTrace();
                            }

                        }
                    }

                }
            }
        };
        t1.start();
        Thread main = Thread.currentThread();
        Thread t2 = new Thread() {
            @Override
            public void run() {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("收到打断信号");
                }
                main.interrupt();
                System.out.println("interrupt");
            }
        };
        t2.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
}
